package common

import (
	"bytes"
	"errors"
	"io/ioutil"
	"net"
	"net/http"
	"time"
)

func HttpSend(url string, postData []byte, header http.Header, timeout time.Duration, connTimeout time.Duration) ([]byte, http.Header, int, error) {
	client := &http.Client{
		Transport: &http.Transport{
			//DisableKeepAlives: true, //拒绝保活
			Dial: func(netw, addr string) (net.Conn, error) {
				//读写超60秒则超时
				deadline := time.Now().Add(timeout)
				//5秒未连接成功则超时
				conn, err := net.DialTimeout(netw, addr, connTimeout)
				if err != nil {
					return nil, err
				}
				conn.SetDeadline(deadline)
				return conn, nil
			},
		},
	}

	var req *http.Request
	var err error
	if len(postData) == 0 {
		req, err = http.NewRequest("GET", url, bytes.NewReader(postData))
		if err != nil {
			return nil, nil, 0, err
		}
	} else {
		req, err = http.NewRequest("POST", url, bytes.NewReader(postData))
		if err != nil {
			return nil, nil, 0, err
		}
	}
	if len(header) > 0 {
		for k, v := range header {
			for _, vi := range v {
				req.Header.Add(k, vi)
			}
		}
	} else {
		req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	}
	//req.Close = true //拒绝保活

	resp, err := client.Do(req)
	if resp == nil || resp.Body == nil {
		return nil, nil, 0, errors.New("resp is nil")
	}
	defer resp.Body.Close()

	if err != nil {
		return nil, nil, 0, err
	}

	buf, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, nil, 0, err
	}

	return buf, resp.Header, resp.StatusCode, err
}
